import {useLocation, useNavigate} from "react-router-dom";
import {useEffect, useState} from "react";
import InputIcon from "@src/components/inputIcon";
import SearchIcon from "@src/assets/search.svg?react"
import {useRequest} from "ahooks";
import {search, songsType} from "@src/services/music.ts";
import MusicCard from "@src/components/musicCard";
import Return2Icon from "@src/assets/return2.svg?react"
import "./index.scss"
import InView from "@src/components/InView";
import {debounce} from "@src/utils/method.ts"

export default function Search() {
    const location = useLocation();
    const navigate = useNavigate();
    const searchApi = useRequest(search, {manual: true})
    const [searchApiData, setSearchApiData] = useState<songsType[]>([])
    const [offset, setOffset] = useState(0);

    const getSearchApi = (offset: number) => {
        if (location.state !== null) {
            searchApi.runAsync(location.state, 30, 30 * offset).then((data) => {
                if (data.result.songs) {
                    setSearchApiData((item) => {
                        const newItem = [...item, ...data.result.songs]
                        const newSongsType = Array.from(new Set(newItem.map(item => item.id))).map(id => {
                            return newItem.find(item => item.id === id);
                        })
                        if (newSongsType.length > 0) {
                            return newSongsType as songsType[]
                        }
                        return newItem

                    })
                    setOffset(offset + 1)
                }
            })
        }
    }


    const AddSearchApi = debounce(() => {
        if (!searchApi.loading) {
            getSearchApi(offset)
        }
    }, 1000)


    useEffect(() => {
        getSearchApi(offset)
    }, [])

    return <div className="search">

        <div className="head centered">
            <Return2Icon onClick={() => navigate("/home/music")}></Return2Icon>
            <InputIcon readOnly defaultValue={location.state} onClick={() => navigate(-1)}
                       Icon={<SearchIcon></SearchIcon>}
                       placeholder="搜索你想找的歌">
            </InputIcon>
        </div>


        <ul>
            {searchApiData.map(song => (
                <li key={song.id}><MusicCard songs={song}></MusicCard></li>
            ))}
        </ul>
        <InView onChange={(e) => {
            if (e) AddSearchApi()
        }}>
            <div className="text-overflow-1">玩命加载中 (╯°□°）╯︵ ┻━┻</div>
        </InView>
    </div>
}